//
//  OrderDetailViewController.m
//  PPDL
//
//  Created by 王洋 on 2019/7/24.
//  Copyright © 2019 王洋. All rights reserved.
//

#import <WXApi.h>

#import "OrderDetailStatusCell.h"
#import "OrderDetailAddressCell.h"
#import "OrderDetailGoodInfoCell.h"
#import "OrderLabShowCell.h"
#import "OrderProgressCell.h"
#import "OrderDetailPriceCell.h"

#import "GoodDetailViewController.h"
#import "OrderDetailViewController.h"
#import "SelPayMethodViewController.h"
#import "LogisticsInfoViewController.h"
#import "AddressManagerViewController.h"

#import "HomeSubscriptButton.h"

typedef NS_ENUM(unsigned long, PPOrderDetailCellType) {
    OrderDetail_StatusCell       = 0,
    OrderDetail_ProgressCell     = 1,
    OrderDetail_AddressCell      = 2,
    OrderDetail_GoodInfoCell     = 3,
    OrderDetail_LabShowCell      = 4,
    OrderDetail_PriceShowCell    = 8,
};

@interface OrderDetailViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) HomeSubscriptButton *shareItem;

@property (weak, nonatomic) IBOutlet UITableView *tableview;

@property (weak, nonatomic) IBOutlet UIButton *actionBtn;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *actionBtnWidth;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomHeightConstraint;

@property (nonatomic, strong) NSMutableArray <OrderDetailNormalInfoModel *> *bottomConfigArray;

@property (nonatomic, strong) AddressItemModel *addressModel;

@property (nonatomic, strong) OrderDetailGoodInfoModel *goodsInfomodel;

@property (nonatomic, strong) OrderDetailNormalInfoModel *statusModel;

@end

@implementation OrderDetailViewController

-(void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"payResultNotification" object:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];

    [self initView];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(payResultCallBack:) name:@"payResultNotification" object:nil];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self request_OrderDetailData];
}

-(void)payResultCallBack:(NSNotification *)Noti {
    
    [self request_OrderDetailData];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"orderRefreshNoti" object:nil userInfo:nil];
}

- (void)goShare {
    
    if ([WXApi isWXAppInstalled]) {
        
        [self shareUrl];

    } else {
        [self alert:@"未安装微信客户端"];
    }
}

#pragma mark REQUEST ------------------ ORDER DETAIL ------------------------
- (void)request_OrderDetailData {
    
    NSMutableDictionary *dic = @{}.mutableCopy;
    [dic setValue:self.orderID forKey:@"id"];

    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,TT_ORDER_DETAIL];
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
        [[TTNoResultManager shareManager] hideNoResultWithView:self.view];

        if ([data isKindOfClass:[NSDictionary class]]) {
            
            NSString * code = [data valueForKey:@"code"];
            if ([code isEqualToString:@"200"]) {
                
                NSDictionary *resultDic = [data valueForKey:@"data"];
                if ([resultDic isKindOfClass:[NSDictionary class]]) {
                    
                    self.addressModel.addressName = [resultDic valueForKey:@"name"];
                    self.addressModel.addressDesc = [resultDic valueForKey:@"address"];
                    self.addressModel.addressPhone = [resultDic valueForKey:@"phone"];
                    
                    self.orderDetailType = [[resultDic valueForKey:@"status"] integerValue];
                    [self refreshViewWithType:self.orderDetailType];

                    self.goodsInfomodel.itemSupplyName = [resultDic valueForKey:@"supplierName"];
                    self.goodsInfomodel.itemMainImage = [resultDic valueForKey:@"goodsImg"];
                    self.goodsInfomodel.itemGoodName = [resultDic valueForKey:@"goodsName"];
                    self.goodsInfomodel.itemFinalPrice = [[resultDic valueForKey:@"price"] doubleValue];
                    self.goodsInfomodel.itemFreightPrice = [[resultDic valueForKey:@"freight"] doubleValue];
                    
                    double total = [[resultDic valueForKey:@"price"] doubleValue] + [[resultDic valueForKey:@"freight"] doubleValue];
                    self.goodsInfomodel.itemTotalPrice = total;
                    self.goodsInfomodel.itemGoodsID = [resultDic valueForKey:@"auctionInfoId"];
                    self.goodsInfomodel.itemLogisticsID = [resultDic valueForKey:@"logisticCode"];
                    
                    self.goodsInfomodel.type =(PPGoodDetailType)[[resultDic valueForKey:@"goodDetailType"] integerValue];
                    
                    NSString *orderType =[NSString stringWithFormat:@"%@",[resultDic valueForKey:@"orderType"]];
                    
                    if ([orderType isEqualToString:@"30"]) {
                        //一拍必得专场的订单可分享，其他订单不可分享
                        UIBarButtonItem * rightItem = [[UIBarButtonItem alloc] initWithCustomView:self.shareItem];
                        self.navigationItem.rightBarButtonItem = rightItem;
                    }
                    
                    self.bottomConfigArray = @[].mutableCopy;
                    OrderDetailNormalInfoModel *orderNumbermodel = [[OrderDetailNormalInfoModel alloc] init];
                    orderNumbermodel.itemTitle = [NSString stringWithFormat:@"订单编号"];
                    orderNumbermodel.itemContent = [NSString stringWithFormat:@"%@",[resultDic valueForKey:@"no"]];
                    [self.bottomConfigArray addObject:orderNumbermodel];
                    
                    OrderDetailNormalInfoModel *orderTimemodel = [[OrderDetailNormalInfoModel alloc] init];
                    orderTimemodel.itemTitle = [NSString stringWithFormat:@"下单时间"];
                    NSString *time = [Utilities getTimeFromTimestamp:[[resultDic valueForKey:@"createTime"] doubleValue]];
                    orderTimemodel.itemContent = time;
                    [self.bottomConfigArray addObject:orderTimemodel];
                    
                    [self.tableview reloadData];
                }
                
            } else {
                
                [SVProgressHUD showErrorWithStatus:[data valueForKey:@"msg"]];
                [SVProgressHUD dismissWithDelay:1];
            }
            
        } else {
            
            [[TTNoResultManager shareManager] showNoResultWithStateInView:self.view errorCode:kTTViewStateNoData btnTitle:@"刷新试试" didPressButton:^{
                [self request_OrderDetailData];
            }];
        }
        
        
    } FailedBlock:^(NSError * _Nonnull error) {
        
        [[TTNoResultManager shareManager] showNoResultWithStateInView:self.view errorCode:error.code btnTitle:@"刷新试试" didPressButton:^{
            [self request_OrderDetailData];
        }];
    }];
}


#pragma mark REQUEST ------------------ ORDER DELETE ------------------------
- (void)request_OrderDelete {
    
    NSMutableDictionary *dic = @{}.mutableCopy;
    [dic setValue:self.orderID forKey:@"id"];

    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,TT_ORDER_DELETE];
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
        
        if ([data isKindOfClass:[NSDictionary class]]) {
            
            NSString * code = [data valueForKey:@"code"];
            if ([code isEqualToString:@"200"]) {

                [[NSNotificationCenter defaultCenter] postNotificationName:@"orderRefreshNoti" object:nil userInfo:nil];
                [self.navigationController popViewControllerAnimated:YES];
                [self alert:[data valueForKey:@"msg"]];
                
            } else {
                
                [SVProgressHUD showErrorWithStatus:[data valueForKey:@"msg"]];
                [SVProgressHUD dismissWithDelay:1];
            }
            
        } else {
            
        }
        
    } FailedBlock:^(NSError * _Nonnull error) {
        
    }];
}

#pragma mark REQUEST ------------------ ORDER RECEIVE ------------------------
- (void)request_OrderReceive {
    
    NSMutableDictionary *dic = @{}.mutableCopy;
    [dic setValue:self.orderID forKey:@"id"];

    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,TT_ORDER_RECEIVE];
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
        
        if ([data isKindOfClass:[NSDictionary class]]) {
            
            NSString * code = [data valueForKey:@"code"];
            if ([code isEqualToString:@"200"]) {
                
                [[NSNotificationCenter defaultCenter] postNotificationName:@"orderRefreshNoti" object:nil userInfo:nil];
                [self.navigationController popViewControllerAnimated:YES];
                [self alert:[data valueForKey:@"msg"]];
                
            } else {
                
                [self alert:[data valueForKey:@"msg"]];
            }
            
        } else {
            
        }
        
    } FailedBlock:^(NSError * _Nonnull error) {
        
    }];
}

#pragma mark REQUEST ------------------ ORDER REMIND SEND ------------------------
- (void)request_OrderRemindSend {
    
    NSMutableDictionary *dic = @{}.mutableCopy;
    [dic setValue:self.orderID forKey:@"id"];

    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,TT_ORDER_REMIND_SEND];
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
        
        if ([data isKindOfClass:[NSDictionary class]]) {
            
            [SVProgressHUD showWithStatus:[data valueForKey:@"msg"]];
            [SVProgressHUD dismissWithDelay:1];
            
        } else {
            
        }
        
    } FailedBlock:^(NSError * _Nonnull error) {
        
    }];
}

#pragma mark REQUEST ------------------ ORDER ADDRESS CHANGE ------------------------
- (void)request_OrderChangeAddressWithID:(NSString *)addressID {
    
    NSMutableDictionary *dic = @{}.mutableCopy;
    [dic setValue:self.orderID forKey:@"orderId"];
    [dic setValue:addressID forKey:@"addrId"];

    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,TT_ORDER_ADDRESS_CHANGE];
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
        
        if ([data isKindOfClass:[NSDictionary class]]) {
                        
            NSString * code = [data valueForKey:@"code"];
            if ([code isEqualToString:@"200"]) {
                
                [SVProgressHUD showWithStatus:[data valueForKey:@"msg"]];
                [SVProgressHUD dismissWithDelay:1];
                
                [self request_OrderDetailData];
                
            } else {

                [self alert:[data valueForKey:@"msg"]];
            }
            
        } else {
            
        }
        
    } FailedBlock:^(NSError * _Nonnull error) {
        
    }];
}

#pragma mark ACTION ------------------ ACTION BTN ------------------------
- (IBAction)orderDetailBottomActionClicked:(id)sender {
    
    switch (self.orderDetailType) {
            
        case ETTOrderDetailType_UnPay:{ //待付款  先判断地址信息是否健全
            
            if (!self.addressModel.addressName.length && !self.addressModel.addressDesc.length && !self.addressModel.addressPhone.length) {

                [self alert:@"请先填好地址再去支付"];
                
            } else {
               
                //根据订单状态来决定下面点击后的action
                SelPayMethodViewController *VC = [[SelPayMethodViewController alloc] init];
                VC.orderId = self.orderID;
                VC.money = [Utilities changeDoubleToString:self.goodsInfomodel.itemTotalPrice];
                VC.payForType = PP_PayType_ForOrder;
                [self.navigationController pushViewController:VC animated:YES];
            }

        } break;
        case ETTOrderDetailType_UnSend:{ //待发货
            
            [self request_OrderRemindSend];
            
        } break;
        case ETTOrderDetailType_UnReceive:{ //待收货
            
            [self request_OrderReceive];
        } break;
        case ETTOrderDetailType_Finish:{ //已完成
            
            [self request_OrderDelete];
            
        } break;
        case ETTOrderDetailType_Invalid:{ //失效
            
            [self request_OrderDelete];
            
        } break;
        default:{
            
            [self alert:@"未知订单状态，请联系客服"];
            
        } break;
    }

}

#pragma mark DELETAGE ------------------ TABLEVIEW DELEGATE ------------------------
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    switch (indexPath.row) {
        case OrderDetail_StatusCell:{
            OrderDetailStatusCell *cell = [tableView dequeueReusableCellWithIdentifier:@"OrderDetailStatusCellID" forIndexPath:indexPath];
            [cell fillCellWithModel:self.statusModel];
            cell.selectionStyle =UITableViewCellSelectionStyleNone;
            
            return cell;
        }break;
        case OrderDetail_ProgressCell:{
            OrderProgressCell *cell = [tableView dequeueReusableCellWithIdentifier:@"OrderProgressCellID" forIndexPath:indexPath];
            cell.orderProgressLab.text = self.statusModel.itemContent;
            cell.selectionStyle =UITableViewCellSelectionStyleNone;
            
            return cell;
        }break;
        case OrderDetail_AddressCell:{
            OrderDetailAddressCell *cell = [tableView dequeueReusableCellWithIdentifier:@"OrderDetailAddressCellID" forIndexPath:indexPath];
            
            [cell fillCellWithModel:self.addressModel];
            cell.selectionStyle =UITableViewCellSelectionStyleNone;
            
            return cell;
        }break;
        case OrderDetail_GoodInfoCell:{
            OrderDetailGoodInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:@"OrderDetailGoodInfoCellID" forIndexPath:indexPath];
            [cell fillCellWithModel:self.goodsInfomodel];
            cell.selectionStyle =UITableViewCellSelectionStyleNone;
            
            return cell;
        }break;
        case OrderDetail_PriceShowCell:{
            OrderDetailPriceCell *cell = [tableView dequeueReusableCellWithIdentifier:@"OrderDetailPriceCellID" forIndexPath:indexPath];
            cell.selectionStyle =UITableViewCellSelectionStyleNone;
            
            return cell;
        }break;
        default:{
            OrderLabShowCell *cell = [tableView dequeueReusableCellWithIdentifier:@"OrderLabShowCellID" forIndexPath:indexPath];
            cell.selectionStyle =UITableViewCellSelectionStyleNone;
            [cell fillCellWithModel:self.bottomConfigArray[indexPath.row - 4]];
            return cell;
        }
            break;
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return  4 + self.bottomConfigArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    switch (indexPath.row) {
        case OrderDetail_StatusCell:{

            return 80;
        }break;
        case OrderDetail_ProgressCell:{

                return 50;

        }break;
        case OrderDetail_AddressCell:{

            return 80;
        }break;
        case OrderDetail_GoodInfoCell:{

            return 220;
        }break;
        default:{

            return 50;
        }
            break;
    }

}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    switch (indexPath.row) {
        case OrderDetail_StatusCell:{
            

        }break;
        case OrderDetail_ProgressCell:{
            
            if ([self.goodsInfomodel.itemLogisticsID isKindOfClass:[NSString class]] && self.goodsInfomodel.itemLogisticsID.length >0) {
                LogisticsInfoViewController *VC = [[LogisticsInfoViewController alloc] init];
                VC.orderID = self.orderID;
                [self.navigationController pushViewController:VC animated:YES];
            } else {
                [self alert:@"暂无物流信息"];
            }
            

            
        }break;
        case OrderDetail_AddressCell:{
            
            if (self.orderDetailType == ETTOrderDetailType_UnPay) {
                
                AddressManagerViewController *VC = [[AddressManagerViewController alloc] init];
                WEAKSELF
                VC.changeAddress = ^(AddressItemModel * _Nonnull model) {
                    
//                    weakSelf.addressModel = model;
//                    [weakSelf.tableview reloadData];
                    
                    [weakSelf request_OrderChangeAddressWithID:model.addressID];
                };
                
                [self.navigationController pushViewController:VC animated:YES];
            }

        }break;
        case OrderDetail_GoodInfoCell:{
            
            GoodDetailViewController *detailVC = [[GoodDetailViewController alloc] init];
            detailVC.goodsID =  self.goodsInfomodel.itemGoodsID;
            detailVC.isFromOrder = YES;
            detailVC.type = self.goodsInfomodel.type;
            [self.navigationController pushViewController:detailVC animated:YES];

        }break;
        case OrderDetail_PriceShowCell:{
            

        }break;
        default:{

        } break;
    }
}

- (void)initView {
    
    self.title = @"订单详情";
    self.bottomHeightConstraint.constant = 50 + kBottomSafeHeight;

    self.actionBtn.layer.cornerRadius = 15;
    self.actionBtn.layer.borderWidth = 1;
    self.actionBtn.layer.borderColor = PP_Default_Color_Red_FF3737.CGColor;
    
    self.tableview.delegate = self;
    self.tableview.dataSource = self;
    self.tableview.backgroundColor = PP_Default_Color_Gray_F1F1F1;
    self.tableview.separatorStyle = UITableViewCellSeparatorStyleNone;

    [self.tableview registerNib:[UINib nibWithNibName:@"OrderDetailStatusCell" bundle:nil] forCellReuseIdentifier:@"OrderDetailStatusCellID"];
    [self.tableview registerNib:[UINib nibWithNibName:@"OrderProgressCell" bundle:nil] forCellReuseIdentifier:@"OrderProgressCellID"];
    [self.tableview registerNib:[UINib nibWithNibName:@"OrderDetailAddressCell" bundle:nil] forCellReuseIdentifier:@"OrderDetailAddressCellID"];
    [self.tableview registerNib:[UINib nibWithNibName:@"OrderDetailGoodInfoCell" bundle:nil] forCellReuseIdentifier:@"OrderDetailGoodInfoCellID"];
    [self.tableview registerNib:[UINib nibWithNibName:@"OrderLabShowCell" bundle:nil] forCellReuseIdentifier:@"OrderLabShowCellID"];
    [self.tableview registerNib:[UINib nibWithNibName:@"OrderDetailPriceCell" bundle:nil] forCellReuseIdentifier:@"OrderDetailPriceCellID"];
    

}

- (void)refreshViewWithType:(ETTOrderDetailType)type {
    
    switch (self.orderDetailType) {
        case ETTOrderDetailType_UnPay:{ //待付款
            
            self.statusModel.itemTitle = @"待付款";
            self.statusModel.itemContent = @"订单将在24小时内失效";
            
            self.actionBtn.hidden = NO;
            [self.actionBtn setTitle:@"去付款" forState:UIControlStateNormal];
            self.actionBtnWidth.constant = 90;
            
        } break;
        case ETTOrderDetailType_UnSend:{ //待发货
            
            self.statusModel.itemTitle = @"待发货";
            self.statusModel.itemContent = @"商家将尽快给您发货";
            
            self.actionBtn.hidden = NO;
            [self.actionBtn setTitle:@"提醒发货" forState:UIControlStateNormal];
            self.actionBtnWidth.constant = 120;
        } break;
        case ETTOrderDetailType_UnReceive:{ //待收货
            
            self.statusModel.itemTitle = @"卖家已发货";
            self.statusModel.itemContent = @"商品还剩7天将确定收货";
            
            self.actionBtn.hidden = NO;
            [self.actionBtn setTitle:@"确认收货" forState:UIControlStateNormal];
            self.actionBtnWidth.constant = 120;
            
        } break;
        case ETTOrderDetailType_Finish:{ //已完成
            self.statusModel.itemTitle = @"交易已经成功";
            self.statusModel.itemContent = @"";
            
            self.actionBtn.hidden = NO;
            [self.actionBtn setTitle:@"删除订单" forState:UIControlStateNormal];
            self.actionBtnWidth.constant = 120;
            
        } break;
        case ETTOrderDetailType_Invalid:{ //失效
            self.statusModel.itemTitle = @"订单已失效";
            self.statusModel.itemContent = @"您的订单因未在规定时间内付款，已失效";
            
            self.actionBtn.hidden = NO;
            [self.actionBtn setTitle:@"删除订单" forState:UIControlStateNormal];
            self.actionBtnWidth.constant = 120;
            
        } break;
        default:{
            self.statusModel.itemTitle = @"未知订单状态，请联系客服";
            self.statusModel.itemContent = @"未知订单状态，请联系客服";
            
            self.actionBtn.hidden = YES;
            
        } break;
    }
    
}

- (OrderDetailGoodInfoModel *)goodsInfomodel {
    if (!_goodsInfomodel) {
        _goodsInfomodel = [[OrderDetailGoodInfoModel alloc] init];
    }
    return _goodsInfomodel;
}

- (AddressItemModel *)addressModel {
    if (!_addressModel) {
        _addressModel = [[AddressItemModel alloc] init];
    }
    return _addressModel;
}

- (NSMutableArray<OrderDetailNormalInfoModel *> *)bottomConfigArray {
    if (!_bottomConfigArray) {
        _bottomConfigArray = @[].mutableCopy;
    }
    return _bottomConfigArray;
}

- (OrderDetailNormalInfoModel *)statusModel {
    if (!_statusModel) {
        _statusModel = [[OrderDetailNormalInfoModel alloc] init];
    }
    return _statusModel;
}

- (HomeSubscriptButton *)shareItem {
    if (!_shareItem) {
        _shareItem = [[HomeSubscriptButton alloc] initWithSize:CGSizeMake(40, 40)];
        [_shareItem.topButton setImage:[UIImage imageNamed:@"share_order"] forState:UIControlStateNormal];;
        _shareItem.userInteractionEnabled = YES;
        [_shareItem setCountNum:0];
        [_shareItem.topButton addTarget:self action:@selector(goShare) forControlEvents:UIControlEventTouchUpInside];
    }
    return _shareItem;
}

- (void)shareUrl {
    
    WXWebpageObject *webpageObject = [WXWebpageObject object];
    webpageObject.webpageUrl = [NSString stringWithFormat:@"%@%@?userId=%@&aid=%@&goodDetailType=%@&recommandId=%@&fromWhere=1",TT_Global_H5_Domain,TT_HTML_SHARE_ORDER,[TTUserModel sharedObject].userID,self.goodsInfomodel.itemGoodsID,@(self.goodsInfomodel.type),[TTUserModel sharedObject].recommandCode];
    WXMediaMessage *message = [WXMediaMessage message];
    message.title =[NSString stringWithFormat:@"我在拍拍得利里以%@元拿走“%@”！人人有份！这里商品价格统统你来定！",self.goodsInfomodel.itemTotalPrice,self.goodsInfomodel.itemGoodName];
    message.description = @"#一拍必得#平台承诺：成交价再低，平台也含泪发货！";
    UIImage *imageP = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:self.goodsInfomodel.itemMainImage]]];
    [message setThumbImage:imageP];
    
    message.mediaObject = webpageObject;
    SendMessageToWXReq *req = [[SendMessageToWXReq alloc] init];
    req.bText = NO;
    req.message = message;
    req.scene = WXSceneSession;
    [WXApi sendReq:req];
    
}

@end
